package com.sample.generator.template.impl;

import java.io.IOException;
import java.util.Properties;

import com.sample.generator.GenerationFailureException;
import com.sample.generator.config.TemplateConfig;
import com.sample.generator.io.InputStreamProvider;
import com.sample.generator.io.ResourceInputStreamProvider;
import com.sample.generator.template.TemplateProcessor;
import com.sample.generator.util.PropertiesLoader;

public abstract class AbstractTemplateProcessor implements TemplateProcessor {

	private TemplateConfig templateConfig;

	public void setTemplateConfig(TemplateConfig templateConfig)
			throws GenerationFailureException {

		if (templateConfig == null) {
			throw new IllegalArgumentException(
					"Argument templateConfig is null.");
		}
		this.templateConfig = templateConfig;
	}

	public TemplateConfig getTemplateConfig() {

		assert templateConfig != null : "templateConfig is null.";
		return templateConfig;
	}

	protected Properties getInitProperties(TemplateConfig config) {

		Properties props = getDefaultProperties();
		try {
			props.putAll(config.getProperties());
			return props;
		} catch (IOException e) {
			throw new GenerationFailureException(e);
		}
	}

	protected Properties getDefaultProperties() {

		InputStreamProvider provider = new ResourceInputStreamProvider(
				getClass());
		PropertiesLoader loader = new PropertiesLoader(provider);
		try {
			return loader.loadProperties("default.properties");
		} catch (IOException e) {
			throw new GenerationFailureException(e);
		}
	}
}
